<?php

namespace app\api\service;

use app\common\model\Order;
use app\common\model\Product;
use app\common\model\Shop;
use app\common\model\User;
use app\Response;

class OrderService
{
    /** 订单列表
     * @param $user_id int 用户ID
     * @param $tid int 抖音号ID
     * @param $page int 页码
     * @param $num int 个数
     * @return array
    */
    public static function orderListService($user_id,$page,$num,$state){
        $userInfo = User::userInfo(["uid"=>$user_id]);
        if($userInfo['type'] != 23){
            return Response::wrapError(0,"账户非达人用户!");
        }
        if($userInfo['enable'] == 0){
            return Response::wrapError(-200,"此账户已被禁用,如有疑问请联系平台客服!");
        }
        $where[] = ["enable","=",1];
        $where[] = ["uid","=",$user_id];
        if(!empty($state)){
            $where[] = ["state","=",$state];
        }
        $list = Order::dataList($where,$page,$num,"*");
        if(!empty($list)){
            $data = $list->toArray();
            foreach ($data as $k => $v){
                $data[$k]["addtime"] = !empty($v["addtime"])?date("Y-m-d H:i:s",$v["addtime"]):"";
            }
            $count = Order::dataCount($where);
        }else{
            $data = [];
            $count = 0;
        }
        return Response::wrapData($data,$count);
    }

    /** 下单
     * @param $data array 下单参数
     * @return json
     */
    public static function robOrderService($data,$user_id){
        $userInfo = User::userInfo(["uid"=>$user_id]);
        if($userInfo['type'] != 23){
            return Response::wrapError(0,"账户非达人用户!");
        }
        if($userInfo['enable'] == 0){
            return Response::wrapError(-200,"此账户已被禁用,如有疑问请联系平台客服!");
        }
        $p_info = Product::dataInfo(["id"=>$data["id"]]);
        if(empty($p_info)){
            return Response::wrapError(0,"商品信息异常!");
        }
        $shop = Shop::dataInfo();
        $order_data = [
            "uid" => $user_id,
            "u_type" => $userInfo['type'],
            "p_id" => $data["id"],
            "p_name" => $data["p_name"],
            "p_num" => $p_info["p_num"],
            "sup_price" => $p_info["supply_price"],
            "order_quantity" => $data["num"],
            "low_price" => bcsub($p_info["supply_price"],$data["num"]),
            "o_pro_num" => self::createOrderNumber(),
            "state" => 0,
            "addtime" => time()
        ];
        $res = Order::addInfo($order_data);
        if($res){
            return Response::wrapData();
        }else{
            return Response::wrapError(0,"下单操作失败");
        }
    }


    public static function createOrderNumber(){
        $orderNumber = time().mt_rand(10000,99999);
        $check = Order::dataInfo(["o_pro_num"=>$orderNumber]);
        if(!empty($check)) {
            self::createOrderNumber();
        } else {
            return $orderNumber;
        }
    }


}